/*
* @Author: Yejing
* @Date: 2023-06-03 18:22:16
* @LastEditors: Yejing
* @LastEditTime: 2023-06-12 15:55:47
* @Description: 上传头像
*/
<template>
	<view class="edit-avator-page">
		<!-- 头部 -->
		<c-navigation-bar :title="$t('user.ProfileEditor')" navbar-bg-color="" title-color="#fff" left-icon-color="#fff">
		</c-navigation-bar>
		<!-- 头像 -->
		<u-avatar :src='vuex_user_info.avatar?$u.file.getMedieUrl(vuex_user_info.avatar):$u.file.getMedieUrl(vuex_userDefaultTopImg)' mode="square" size="750" @click="select"></u-avatar>
		<!-- 控件 -->
		<ksp-cropper mode="free" :width="750" :height="750" :maxWidth="1024" :maxHeight="1024" :url="url" @cancel="oncancel"
			@ok="onok">
		</ksp-cropper>
	</view>
</template>

<script>
	import { base64toFile, base64ToPath } from 'image-tools'
	import COS from '@/static/js/COS.js'
	export default {
		data() {
			return {
				url: "",
				avatar: ''
			}
		},
		computed: {
			
		},
		methods: {
			select() {
				uni.chooseImage({
					count: 1,
					success: (rst) => {
						console.log(rst)
						// 设置url的值，显示控件
						this.url = rst.tempFilePaths[0];
					}
				});
			},
			base64toFile(dataurl, filename = 'file') {
				console.log(dataurl)
				let arr = dataurl.split(',')
				let mime = arr[0].match(/:(.*?);/)[1]
				let suffix = mime.split('/')[1]
				let bstr = atob(arr[1])
				let n = bstr.length
				let u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new File([u8arr], `${filename}.${suffix}`, {
					type: mime
				})
			},
			onok(ev) {
				let that=this
				let filePath = this.url;
				let filename = filePath.substr(filePath.lastIndexOf('/') + 1);
				COS.uploadFileToTencentClound(filename, filePath,'user_top').then((res) => {
					console.log(res)
					that.$u.put('/app/user/edit', {
						avatar: res.split(`${process.uniEnv.COSBucket}.cos.${process.uniEnv.COSRegion}.myqcloud.com/`)[1]
					}).then(r => {
						that.$u.init.getUserInfo()
						that.publicJS.backOption()
					});
				})

			
			},

			oncancel() {
				// url设置为空，隐藏控件
				this.url = "";
			},

		}
	}
</script>

<style lang="scss" scoped>
	.edit-avator-page {
		background-color: #1B1D29;
		height: 100vh;
		color: #fff;

		/deep/ .u-avatar {
			display: block;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);

			uni-image {
				overflow: inherit;
			}
		}
	}
</style>